package leetcode.L39;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

class Solution1 {
    private List<List<Integer>> res = new ArrayList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        if (candidates.length == 0) return res;
        Arrays.sort(candidates);
        backTrack(candidates, target, 0, 0);
        return res;
    }

    List<Integer> currRes = new LinkedList<>();

    private void backTrack(int[] candidates, int target, int sum, int index) {
        if (sum == target) {
            res.add(new ArrayList<>(currRes));
            return;
        }
        for (int i = index; i < candidates.length; i++) {
            if (sum + candidates[i] > target) break;
            currRes.add(candidates[i]);
            sum += candidates[i];
            backTrack(candidates, target, sum, i);
            currRes.remove(currRes.size() - 1);
            sum -= candidates[i];
        }
    }
}